#include "OpenGL.h"

#define VERTEX(x,y,tx,ty) glTexCoord2f(x,y); \
					glVertex2f(tx,ty);

GLuint OpenGL::SDL_SurfaceToTexture(sprite *spr) {
	Uint32 rmask, gmask, bmask, amask;
	SDL_Surface * temp = NULL;
	SDL_Surface * tempalpha = NULL;
	GLuint texture;
	if (Endian::Kind() == Endian::Kind::BIG) {
		rmask = 0xff000000;
		gmask = 0x00ff0000;
		bmask = 0x0000ff00;
		amask = 0x000000ff;
	} else {
		rmask = 0x000000ff;
		gmask = 0x0000ff00;
		bmask = 0x00ff0000;
		amask = 0xff000000;
	}
	tempalpha = SDL_DisplayFormatAlpha(spr->texture);
	SDL_SetAlpha(tempalpha, 0, SDL_ALPHA_TRANSPARENT);
	temp = SDL_CreateRGBSurface(SDL_SWSURFACE, spr->width, spr->height,
								32, bmask, gmask, rmask, amask);
	SDL_BlitSurface(tempalpha, NULL, temp, NULL);
	
	SDL_FreeSurface(tempalpha);
	
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	SDL_LockSurface(temp);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels);
	SDL_UnlockSurface(temp);
	SDL_FreeSurface(temp);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	return texture;
}

void OpenGL::drawSprite(sprite *spr, double x, double y, bool relative) {
	glPushMatrix();
	if(relative){
		glTranslated(-view.x,-view.y,0);
	}
    glTranslated(x,y,0);
    glTranslated(-spr->originx,-spr->originy,0);
    glBindTexture(GL_TEXTURE_2D,spr->glget());
	glColor4f(1,1,1,1);
    glBegin(GL_QUADS);
	{
		glTexCoord2f(0,0);
		glVertex2i(0,0);
		glTexCoord2f(spr->twidth,0);
		glVertex2i(spr->width,0);
		glTexCoord2f(spr->twidth,spr->theight);
		glVertex2i(spr->width,spr->height);
		glTexCoord2f(0,spr->theight);
		glVertex2i(0,spr->height);
	}
    glEnd();
    glLoadIdentity();
    if(glGetError()!=GL_NO_ERROR){
            cout << "ERROR" << endl;
    }
	glPopMatrix();
}